<template>
  <div>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:setting-filled',
                tooltip: {
                  title: '配置仪表盘',
                  placement: 'top',
                },
                onClick: handleAllocation.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PublicDrawer @register="registerDrawer" @updateDescData="handleUpdateDescData" />
  </div>
</template>

<script lang="ts" setup>
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { dashboardParams } from '/@/api/thingsborad/dashboards/model/dashboardModel';
  import { getDashboard, getCustomerDashboard } from '/@/api/thingsborad/dashboards/dashboard';
  import { onMounted, ref } from 'vue';
  import dayjs from 'dayjs';
  import { useDrawer } from '/@/components/Drawer';
  import { useRoute } from 'vue-router';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { dashboardColumns, searchFormSchema } from './dashboards.data';
  import { useGo } from '/@/hooks/web/usePage';
  import { useUserStore } from '/@/store/modules/user';
  const go = useGo();
  const checkedKeys = ref<any>([]);
  let params = ref<dashboardParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
    type: 'CORE',
  });
  let tableData = ref<Array<any>>([]);
  const route = useRoute();
  onMounted(() => {
    const userStore = useUserStore();

    // 获取用户登录信息
    const userInfo = userStore.userInfo;
    // 初始化表格数据
    if (route.params.id === undefined) {
      setProps({
        api: getCustomerDashboard,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          let data: any = {
            params: params.value,
            id: userInfo?.customerId,
          };
          return data;
        },
        afterFetch: (res) => {
          tableData.value = [];
          if (res.length === 0) {
            return tableData.value;
          }

          res.forEach((item) => {
            tableData.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              title: item.title,
              public:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? false
                  : item.assignedCustomers[0].public,
              assignedCustomers:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? '--'
                  : item.assignedCustomers[0].title,
              id: item.id.id,
              info: item,
            });
          });

          return tableData.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
    } else {
      setProps({
        api: getDashboard,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          let data: any = {
            params: params.value,
            id: userInfo?.customerId,
          };
          return data;
        },
        afterFetch: (res) => {
          tableData.value = [];
          if (res.length === 0) {
            return tableData.value;
          }
          res.forEach((item) => {
            tableData.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              title: item.title,
              public:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? false
                  : item.assignedCustomers[0].public,
              assignedCustomers:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? '--'
                  : item.assignedCustomers[0].title,
              id: item.id.id,
              info: item,
            });
          });

          return tableData.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
    }
  });
  const [registerDrawer] = useDrawer();
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    title: '仪表盘',
    columns: dashboardColumns,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 抽屉详情数据更改
  const handleUpdateDescData = (value) => {
    value.assetName = value.name;
    value.assetConfiguration = value.assetProfileName;
    value.label = value.label;
    value.customer = value.customerTitle;
    value.isOpen = value.customerIsPublic;
  };

  function handleAllocation(record: Recordable) {
    go({
      name: 'ConfigureDashboard',
      params: {
        id: record.id,
      },
    });
  }
</script>
